<script setup>
import {reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import useFileUpload from "@/utiles/common.js";
import {getRei, saveRei, updateRei} from "@/api/reimburse.js";
import {eventBus} from "@/utiles/eventBus.js";

// 控制对话框显示/隐藏
const dialogVisible = ref(false)
const applyId = ref(null)
const planId = ref(null)
const reiId = ref(null)
// 响应式数据
const fileInput = ref(null)
const uploadedImages = ref([]) // 存储所有上传的图片信息
const invoices = ref([])
const zoomedImage = ref(null) // 当前放大的图片URL
const amount = ref()
const detail = ref()

// 使用您提供的文件上传钩子
const imageUpload = useFileUpload({
  endpoint: 'http://localhost:8081/common/upload',
  extraData: {type: 'invoice'},
  maxSize: 2 * 1024 * 1024,
  allowedTypes: ['image/jpeg', 'image/png', 'image/jpg']
})


// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)

  if (files.length === 0) return

  // 验证文件并添加到上传队列
  files.forEach(file => {

    // 添加到上传列表，状态为待上传
    uploadedImages.value.push({
      file,
      name: file.name,
      url: URL.createObjectURL(file), // 创建预览URL
      status: 'pending' // pending, uploading, success, error
    })
  })

  // 重置文件输入，允许再次选择相同文件
  event.target.value = ''

  // 自动开始上传
  uploadPendingImages()
}

// 上传所有待处理的图片
const uploadPendingImages = async () => {
  const pendingImages = uploadedImages.value.filter(img => img.status === 'pending')

  for (const image of pendingImages) {
    await uploadSingleImage(image)
  }

}

// 上传单个图片
const uploadSingleImage = async (image) => {
  try {
    // 更新状态为上传中
    image.status = 'uploading'

    // 调用上传函数
    const url = await imageUpload.upload(image.file)

    // 更新状态为成功，并保存服务器返回的URL
    image.status = 'success'
    image.serverUrl = url
    console.log(`图片 "${image.name}" 上传成功:`, url)

  } catch (error) {
    // 更新状态为失败
    image.status = 'error'
    console.error(`图片 "${image.name}" 上传失败:`, error)
    alert(`图片 "${image.name}" 上传失败，请重试`)
  }
}

// 删除图片
const removeImage = (index) => {
  // 释放预览URL的内存
  if (uploadedImages.value[index].url.startsWith('blob:')) {
    URL.revokeObjectURL(uploadedImages.value[index].url)
  }

  uploadedImages.value.splice(index, 1)
}
// 放大图片
const zoomImage = (imageUrl) => {
  zoomedImage.value = imageUrl
}

// 关闭放大图片
const closeZoom = () => {
  zoomedImage.value = null
}

// 阻止事件冒泡（防止点击图片时触发关闭）
const stopPropagation = (event) => {
  event.stopPropagation()
}

// 打开对话框
const openDialog = (aId, pId, rId) => {
  dialogVisible.value = true
  applyId.value = aId
  planId.value = pId
  reiId.value = rId
  // 打开对话框的其他逻辑
  console.log('接收到的参数:', applyId.value, planId.value, reiId)
  if (rId != null)
    editRei()

}

const editRei = async () => {
  const {data} = await getRei(reiId.value)
  console.log(data)
  amount.value = data.data.amount
  detail.value = data.data.detail
  invoices.value = data.data.invoices
  applyId.value = data.data.applyId
  planId.value = data.data.planId
}

const removeInvoice = async (id, event) => {
  if (event) {
    event.preventDefault()
    event.stopPropagation()
  }
  await ElMessageBox.confirm(
    '确定要删除这张发票吗？此操作不可恢复。',
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  )

  // 找到要删除的发票索引
  const invoiceIndex = invoices.value.findIndex(invoice => invoice.id === id)

  // 从数组中移除
  invoices.value.splice(invoiceIndex, 1)

  ElMessage.success('发票删除成功')
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  amount.value = ''
  detail.value = ''
  uploadedImages.value = []
  invoices.value = []
}

// 提交报销
const submitReimbursement = async () => {
  // 表单验证
  if (!amount.value) {
    ElMessage.error('请输入报销金额')
    return
  }

  if (!detail.value) {
    ElMessage.error('请输入报销明细')
    return
  }

  const invoiceUrls = uploadedImages.value.map(image => image.serverUrl)

  const rei = ref({
    applyId: applyId.value,
    planId: planId.value,
    amount: amount.value,
    detail: detail.value,
    invoiceUrls: invoiceUrls
  })

  const data = await saveRei(rei.value)
  console.log(data)


  ElMessage.success('报销申请提交成功')

  if (eventBus.value.refreshApplies) {
    eventBus.value.refreshApplies()
  }

  // 关闭对话框
  closeDialog()
}

const updateReimbursement = async () => {
  // 表单验证
  if (!amount.value) {
    ElMessage.error('请输入报销金额')
    return
  }

  if (!detail.value) {
    ElMessage.error('请输入报销明细')
    return
  }

  uploadedImages.value.forEach(image => {
    // 只处理成功上传的图片
    if (image.serverUrl) {
      // 创建新的 invoice 对象
      const newInvoice = {
        id: null, // 生成唯一ID
        reiId: reiId.value,     // 使用已有的 reiId
        invoiceImg: image.serverUrl // 使用服务器返回的URL
      }

      // 逐个添加到 invoices 数组
      invoices.value.push(newInvoice)
    }
  })

  uploadedImages.value=[]

  const rei = ref({
    id: reiId,
    applyId: applyId.value,
    planId: planId.value,
    amount: amount.value,
    detail: detail.value,
    invoices: invoices.value
  })

  const data = await updateRei(rei.value)

  if (eventBus.value.refreshApplies) {
    eventBus.value.refreshApplies()
  }

  ElMessage.success('报销项更新成功')

  // 关闭对话框
  closeDialog()
}

// 暴露方法，供父组件调用
defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="快速报销"
    width="600px"
    :before-close="closeDialog"
    center
  >
    <el-form label-width="80px">
      <el-form-item label="报销金额" required>
        <el-input
          v-model="amount"
          placeholder="请输入报销金额"
          style="width: 200px"
        >
          <template #prepend>¥</template>
        </el-input>
      </el-form-item>

      <el-form-item label="报销明细" required>
        <el-input
          v-model="detail"
          type="textarea"
          :rows="4"
          placeholder="请输入详细的报销明细，如：交通费、住宿费等"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <div class="image-upload-container">
        <div class="image-list">
          <div v-for="(invoice, index) in invoices"
               :key="index"
               class="image-item">
            <div class="image-preview" @click="zoomImage(invoice.invoiceImg)">
              <img :src="invoice.invoiceImg" :alt="`上传图片 ${index + 1}`"/>
              <div class="image-overlay">
                <button class="delete-btn" @click.stop="removeInvoice(invoice.id, $event)"
                        title="删除图片">
                  ×
                </button>
              </div>
            </div>
          </div>
          <div
            v-for="(image, index) in uploadedImages"
            :key="index"
            class="image-item"
          >
            <div class="image-preview" @click="zoomImage(image.url)">
              <img :src="image.url" :alt="`上传图片 ${index + 1}`"/>
              <div class="image-overlay">
                <button class="delete-btn" @click.stop="removeImage(index)" title="删除图片">
                  ×
                </button>
              </div>
            </div>
          </div>

          <div class="upload-area" @click="triggerFileInput">
            <div class="upload-content">
              <i class="upload-icon">+</i>
              <p class="upload-text">点击上传图片</p>
              <p class="upload-hint">支持 JPG、PNG 格式<br>单张图片不超过 2MB</p>
            </div>
            <input
              ref="fileInput"
              type="file"
              accept="image/jpeg, image/png, image/jpg"
              multiple
              @change="handleFileSelect"
              class="file-input"
            />
          </div>
        </div>
      </div>

    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <span v-if="reiId">
          <el-button type="primary" @click="updateReimbursement">
          更新报销
          </el-button>
        </span>
        <span v-else>
          <el-button type="primary" @click="submitReimbursement">
          提交报销
        </el-button>
        </span>

      </span>
    </template>
  </el-dialog>
  <div v-if="zoomedImage" class="image-modal" @click="closeZoom">
    <div class="modal-content" @click.stop="stopPropagation">
      <button class="close-btn" @click="closeZoom">×</button>
      <img :src="zoomedImage" alt="放大预览" class="zoomed-image"/>
    </div>
  </div>
</template>

<style scoped>

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.image-upload-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;


}


.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  flex: 1;

  .image-item {
    width: 120px;
    overflow: hidden;

    .image-preview {
      position: relative;
      height: 120px;
      overflow: hidden;
    }

    .image-preview img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }

    .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      display: flex;
      align-items: flex-start;
      justify-content: flex-end;
      opacity: 0;
      transition: opacity 0.3s ease;
      border-radius: 8px;
    }

    .image-preview:hover .image-overlay {
      opacity: 1;
    }


    .delete-btn {
      position: absolute;
      top: 5px;
      right: 5px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: rgba(255, 0, 0, 0.7);
      color: white;
      border: none;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      line-height: 1;
    }

    .delete-btn:hover {
      background: rgba(255, 0, 0, 0.9);
    }
  }

  /* 右侧上传框 */

  .upload-area {
    width: 120px;
    height: 120px;
    border: 2px dashed #ccc;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background-color: #f9f9f9;
    flex-shrink: 0;


    .upload-content {
      text-align: center;
      pointer-events: none;
    }

    .upload-icon {
      font-size: 36px;
      color: #909399;
      margin-bottom: 8px;
      display: block;
    }

    .upload-text {
      font-size: 14px;
      color: #606266;
      margin-bottom: 5px;
    }

    .upload-hint {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
    }

    .file-input {
      display: none;
    }


  }

  .upload-area:hover {
    border-color: #409eff;
    background-color: #f0f8ff;
  }


}

.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  animation: fadeIn 0.3s ease;

  .modal-content {
    position: relative;
    max-width: 90%;
    max-height: 90%;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: zoomIn 0.3s ease;
    z-index: 100;
  }

  @keyframes zoomIn {
    from {
      transform: scale(0.8);
      opacity: 0;
    }
    to {
      transform: scale(1);
      opacity: 1;
    }
  }

  .zoomed-image {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
    z-index: 101;
  }

  .close-btn {
    position: absolute;
    top: -10px;
    right: -20px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    line-height: 1;
    transition: background 0.3s ease;
  }

  .close-btn:hover {
    background: rgba(255, 255, 255, 0.3);
  }


}


</style>
